<template>
<a-spin size="large" :delay="1000" :spinning="spinning" >
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24" >
            <a-form-item label="流程名称">
              <a-input v-model="queryParam.name" placeholder="请输入流程名称"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="流程编码">
              <a-input v-model="queryParam.key" placeholder="请输入流程编码"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button  type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" icon="reload" style="margin-left: 8px" @click="searchReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('在线图表')">导出</a-button>
      <a-upload name="file" :show-upload-list="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import" >导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button>批量操作<a-icon type="down" /></a-button>
      </a-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon" />
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px"  @click="onClearSelected">清空</a>
      </div>
      <a-table
        size="middle"
        bordered
        row-key="id"
        :columns="columns"
        :data-source="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <!-- online表单不需要设计表单 -->
          <a @click="editForm(record)" v-if="!record.formType || record.formType  ==='0'">设计表单</a>
          <a-divider type="vertical"  v-if="!record.formType || record.formType  ==='0' " />
          <a @click="editProcess(record)">设计流程</a>
          <a-divider type="vertical" />
          <a @click="configProcess(record)">流程配置</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleStart(record.id)">发布</a>
              </a-menu-item>
              <a-menu-item>
                <a>版本监控</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleConfigPrint(record)">打印配置</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleOnlineUrlShow(record.id)">配置地址</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleFormData(record)">表单数据</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a >删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <j-modal
      title="表单设计器"
      :fullscreen.sync="fullscreen"
      :visible.sync="isIframeLoaded"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
      :footer="null"
      :bodyStyle="{'padding':'0px'}"
    >
    <a-spin :spinning="spinning">
      <k-form-design ref="kfd" @save="handleSubmitKFD" :showHead="false"  />
    </a-spin>
    </j-modal>
    <j-modal
      width="1200"
      title="流程设计器"
      :visible.sync="bpmnVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      :destroyOnClose="true"
      @cancel="handleCancleBpmn"
      :footer="null"
      :bodyStyle="{'padding':'0px','position':'relative'}"
    >
     <a-spin :spinning="spinning">
      <bpmn ref="bpmn" :xml="flowXml" :processData="processData" @ok="handleSubmitBpmn" />
     </a-spin>
    </j-modal>
    <process-model ref="modalForm" @ok="modalFormOk"></process-model>
    <process-config-modal ref="processConfigModel" :processData="processData"></process-config-modal>
     <!-- 提示online报表链接 -->
    <config-url-modal :url="onlineUrl" ref="onlineUrl"></config-url-modal>
  </a-card>
</a-spin>
</template>

<script>
import { getFormByModelId, deployment, getFlowByModelId, saveFlow, saveOrUpdateForm } from '@/api/process'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import processModel from './modal/processModal'
import processConfigModal from './modal/processConfigModal'
import bpmn from '@/components/bpmn/bpmn'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import ConfigUrlModal from '@/components/custom/ConfigUrlModal'
import { KFormDesign } from '@/components/k-form-design/index'
export default {
  name: 'Process',
  components: {
    processModel,
    bpmn,
    processConfigModal,
    ConfigUrlModal,
    KFormDesign
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '流程名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '流程编码',
          align: 'center',
          dataIndex: 'key'
        },
        {
          title: '描述',
          align: 'center',
          dataIndex: 'description'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'processDefinitionId', // processState
          customRender: function(t, r, index) {
            return t ? '已发布' : '未发布'
          }
        },
        {
          title: '表单类型',
          align: 'center',
          dataIndex: 'formType', // processState
          customRender: function(t, r, index) {
            return filterDictTextByCache('sys_form_type', t)
          }
        },
        {
          title: '发布时间',
          align: 'center',
          dataIndex: 'publishTime'
        },
        {
          title: '版本',
          align: 'center',
          dataIndex: 'version'
        },
        {
          title: '业务板块',
          align: 'center',
          dataIndex: 'businessPlate',
          customRender: (text) => {
            return filterDictTextByCache('business_sector', text)
          }
        },
        {
          title: '是否显示',
          align: 'center',
          dataIndex: 'isShow',
          customRender: function(t, r, index) {
            return t ? '是' : '否'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/activiti/models/list',
        deleteBatch: '/activiti/models/deleteBatch',
        delete: '/activiti/models/delete',
        importExcelUrl: '/sys/fillRule/importExcel',
        exportXlsUrl: '/sys/fillRule/exportXls',
        saveForm: '/activiti/form/saveOrUpdateForm', // 自定义表单保存
        getFlow: '/activiti/flow/getFlowByModelId'// 流程查询
      },
      isIframeLoaded: false,
      isIframePreviewLoaded: false,
      fullscreen: true,
      switchFullscreen: true,
      bpmnVisible: false,
      modelId: '',
      KDFJsonId: '',
      flowXml: '',
      processData: {},
      onlineUrl: [], // 配置地址
      spinning: false,
      excludeKeys: ['name', 'key']
    }
  },
  methods: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
    },
    editForm(data) { // 编辑表单设计器
      getFormByModelId({ modelId: data.id, processDefinitionId: data.processDefinitionId }).then((res) => { // 查询已有表单设计器
        if (res.success) {
          this.KDFJsonId = res.result ? res.result.id : null
          this.modelId = data.id
          this.processDefinitionId = data.processDefinitionId
          this.isIframeLoaded = true
          this.$nextTick(() => {
            res.result && this.$refs.kfd.handleSetData(JSON.parse(res.result.htmlJson))
          })
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    editProcess(data) { // 编辑流程
      this.modelId = data.id
      getFlowByModelId({ modelId: data.id }).then((res) => { // 查询已有流程
        if (res.success) {
          this.bpmnVisible = true
          if (res.result !== '{"id":"canvas","resourceId":"canvas","stencilset":{"namespace":"http://b3mn.org/stencilset/bpmn2.0#"}}') {
            this.flowXml = res.result
          } else {
            this.flowXml = ''
          }
          this.processData = data
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    configProcess(record) {
      this.processData = record
      this.$refs.processConfigModel.editModalVisible = true
    },
    handleCancleDbSync() { // 关闭
      this.editModalVisible = false
    },
    handleCancleBpmn() {
      this.bpmnVisible = false
    },
    handleSubmitBpmn(data) { // 流程设计器保存、编辑
      this.spinning = true
      const that = this
      saveFlow({
        modelId: that.modelId,
        json_xml: data.xml,
        svg_xml: 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(data.svg)))
      }).then((res) => {
        if (res.success) {
          that.bpmnVisible = false
          that.$message.success(res.message)
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        setTimeout(() => {
          this.spinning = false
        })
      })
    },
    handleSubmitKFD(data) { // 表单设计器保存
      this.spinning = true
      const kfdData = JSON.parse(data)
      const masterTableId = kfdData.config.onlineFormCode
      const slaveTableIds = this.getSlaveTableId(kfdData.list)
      saveOrUpdateForm({
        htmlJson: data,
        modelId: this.modelId,
        masterTableId: masterTableId,
        slaveTableId: slaveTableIds.join(),
        id: this.KDFJsonId
      }).then((res) => {
        if (res.success) {
          this.isIframeLoaded = false
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        setTimeout(() => {
          this.spinning = false
        })
      })
    },
    getSlaveTableId(list) { // 递归获取附表code
      const that = this
      let slaveTableIds = []
      list.forEach(function(item, i) {
        if (item.type === 'batch' && item.onlineFormCode) {
          slaveTableIds.push(item.onlineFormCode)
        }
        if (item.list) {
          slaveTableIds = slaveTableIds.concat(that.getSlaveTableId(item.list))
        }
      })
      return slaveTableIds
    },
    handleStart(id) { // 流程发布
      const that = this
      this.$confirm({
        title: '确认发布流程',
        content: '是否发布该流程?',
        cancelText: '取消',
        okText: '确定',
        onOk() {
          that.spinning = true
          that.$message.loading({ content: '发布中', key: 'updatable', duration: 0 })
          deployment({ modelId: id }).then((res) => {
            that.spinning = false
            if (res.success) {
              that.loadData()
              that.$message.success({ content: '发布成功', key: 'updatable', duration: 2 })
            } else {
              that.$message.warning(res.message)
            }
          }).catch((error) => {
            console.log(error)
          })
        }
      })
    },
    handleFormData(data) {
      if (data.formType === '0') {
        this.$router.push({ path: '/ProcessList/' + data.id })
      } else if (data.formType === '1') {
        getAction('online/cgform/head/list', { id: data.tableName }).then(res => {
          if (res.success) {
            const url = this.getOnlineUrl(res.result.records[0])
            this.$router.push({ path: url + data.tableName })
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    handleOnlineUrlShow(id) {
      this.onlineUrl = [
        { label: '新增：', url: `/ProcessList/${id}` },
        { label: '办理：', url: `/TaskList/${id}` }
      ]
      this.$refs.onlineUrl.onlineUrlVisible = true
    },
    getOnlineUrl(data) {
      if (data.themeTemplate === 'innerTable') {
        return '/online/cgformInnerTableList/'
      } else if (data.themeTemplate === 'erp') {
        return '/online/cgformErpList/'
      } else {
        if (data.isTree === 'Y') {
          return '/online/cgformTreeList/'
        } else {
          return '/online/cgformList/'
        }
      }
    },
    handleConfigPrint(data) {
      if (!data.processDefinitionId) {
        this.$message.warning('请发布后再配置打印')
        return false
      }
      this.$router.push({
        path: '/online/9cd8afb1fa977115e7a82cc9255483dc'
      })
    }
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
